import { Lose } from '../tips/lose'
import { Pause } from '../tips/pause'
import { DashBoard } from '../dashboard/DashBoard'
import { Checkpoint } from '../checkpoints/checkpoint_two'
import { playBackgroundMusic, pauseBackgroundMusic, playWoodHitMusic } from '../component/music';
import { CanvasButton } from '../component/custombutton'
export const settings = {
    FORCE_OPEN: true,
    MUSIC_OPEN: true
};
export class Checkpoint_one {
    constructor(canvas) {
        // 初始化变量
        this.canvas = canvas;
        this.context = this.canvas.getContext('2d');
        this.width = this.canvas.width;
        this.height = this.canvas.height;

        this.timer = null;
        this.timer = setInterval(() => {
            this.completeTime++;
        }, 1000); // 每1000毫秒（即1秒）执行一次

        //初始化数据
        this.gameOver = false; // 判断游戏结束
        this.countNum = 0;  // 偏移数量
        this.isUpdating = true; // 用于判断是否进行动画渲染
        this.isPausing = false; // 用于判断暂停按钮是否点击
        // this.isBackhome = false; // 用于判断是否返回主页
        this.score = 0; // 当前分数
        this.distanceHeight = 20; // 用于修改小猪和木块的高度差，用来控制整体  难 度
        this.blockNum = 3 + 2; // 用于修改方块数量，前者为方块，后者为固定值地板
        this.playerMoveRange = 5; // 用于修改小猪的移动范围, 定义为木块的数量

        this.percentage = 12 / 100;
        this.iconSize = this.width * this.percentage;  // 用于统一页面图标大小
        this.size_1 = this.width * this.percentage / 2; // 用于调整页面字号大小 （目前仅包含时间）
        // this.size_2 = this.width * this.percentage / 2;
        // this.size_3 = this.width * this.percentage / 2;

        this.completeTime = 0; // 游戏计时

        this.button = [];

        // 玩家和方块的属性
        this.player = {
            x: this.width * this.percentage,
            y: this.height * (1 - this.percentage * 2),
            width: this.iconSize,
            height: this.iconSize,
            speedY: 3, // 控制移动速度，调整难度
            isMovingRight: false
        };

        this.blocks = [];
        wx.showLoading({
          title: '加载中......'
      });
      // 初始化图片数据
      this.onloadImage();
          for (let i = 0; i < this.blockNum; i++) {
              var status = 'wood';
              var random = Math.floor(Math.random() * 9);
              var cube = this.wood;
              if (i >= this.blockNum - 2) {
                  status = 'floor';
              }
              this.blocks.push({
                  x: this.width - this.iconSize * 3,
                  y: this.height - (this.blockNum - i) * (this.iconSize + this.distanceHeight),
                  width: this.iconSize * 2,
                  height: this.iconSize + this.distanceHeight,
                  speedX: 0,
                  speedY: 0,
                  hasCollided: false,
                  angle: 0,
                  angleOffset: 0,
                  status: status,
                  cube: cube
              });
          }

          wx.hideLoading();  
          this.init();
    }

    init() {
        pauseBackgroundMusic();
        if (settings.MUSIC_OPEN === true) { //背景音乐播放状态
            playBackgroundMusic();
        }
       
        this.onloadPage(); // 监听页面点击事件
        this.drawPauseButton();
        this.drawAnimate(); // 开始游戏动画渲染
    }

    //初始化所有图片相关内容，创建等
    onloadImage() {
        let loadedCount = 0;
        const totalImages = 5;
        
        this.wood = wx.createImage();
        this.wood.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/wood.png';
        // this.wood.onload = () => {
        //     loadedCount++;
        //     checkIfAllLoaded();
        // };

        this.background = wx.createImage();
        this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_1.png';
        // this.background.onload = () => {
        //     loadedCount++;
        //     checkIfAllLoaded();
        // };

        this.pause_icon = wx.createImage();
        this.pause_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pause.png'
        // this.pause_icon.onload = () => {
        //     loadedCount++;
        //     checkIfAllLoaded();
        // };

        this.time_icon = wx.createImage();
        this.time_icon.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/time.png'
        // this.time_icon.onload = () => {
        //     loadedCount++;
        //     checkIfAllLoaded();
        // };

        this.pig = wx.createImage();
        this.currentSkinImage = wx.getStorageSync('currentSkinImage');
        console.log(this.currentSkinImage);
        this.pig.src = `${this.currentSkinImage}`;
        // this.pig.onload = () => {
        //     loadedCount++;
        //     checkIfAllLoaded();
        // };

        // const checkIfAllLoaded = () => {
        //     if (loadedCount === totalImages && callback) {
        //         callback();
        //     }
        // };
        
    }
    drawPauseButton() {
      let _this = this;
      let pause ={
        type: "image",
        image: "https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pause.png",
        style: {
            backgroundColor: 'transparent',
            left: this.iconSize / 2,
            top: this.iconSize / 2,
            width: this.iconSize,
            height: this.iconSize
        },
        success(button) {
          _this.button.push(button);
          button.drawButton(_this.context); // 绘制按钮
          button.onTap((res) => {
              button.destroy();
              _this.isPausing = true;
          })
      },
      }
      new CanvasButton(pause);
    }
    // 监听页面点击事件
    onloadPage() {
        // 先移除之前可能存在的触摸事件监听器
        wx.offTouchStart();
        // 监听点击事件
        wx.onTouchStart((e) => {
            const touchX = e.touches[0].clientX;
            const touchY = e.touches[0].clientY;
            // 检查是否点击了暂停按钮的范围内
            if (!(touchX >= this.iconSize / 2 && touchX <= this.iconSize * 3 / 2 && touchY >= this.iconSize / 2 && touchY <= this.iconSize * 3 / 2)) {
                this.player.isMovingRight = true;
            }
        });
    }

    // 绘制木块偏移
    drawBlock(block) {
        this.context.save();
        this.context.translate(block.x + block.width / 2, block.y + block.height / 2);
        this.context.rotate(block.angle);
        this.context.translate(-block.width / 2, -block.height / 2);
        this.context.drawImage(block.cube, 0, 0, block.width, block.height);
        this.context.restore();
    }

    // 绘制帧动画部分
    drawAnimate() {
        // 游戏失败监测
        if (this.isUpdating === false && this.gameOver === true) {
            this.showLosePopup(); // 显示失败弹窗
            return;
        }

        // 游戏暂停监测
        if (this.isPausing === true) {
            this.showPausePopup();
            return;
        }
        // 游戏通关监测
        if (this.score === this.blockNum - 2) {
            for (let index = this.blocks.length - 3; index >= 0; index--) {
                const blockTop = this.blocks[index].y;
                const blockBottom = this.blocks[index].y + this.blocks[index].height;
                const blockLeft = this.blocks[index].x;
                const blockRight = this.blocks[index].x + this.blocks[index].width;
                // 只有当矩形部分或全部可见时才进行绘制
                if (blockBottom >= this.height - this.blocks[3].height * 3 && blockTop <= this.height - this.blocks[3].height * 2 &&
                    blockRight >= 0 && blockLeft <= this.width) {
                    if (this.blocks[index].x > this.width - 5) {
                        this.funGoTwo();
                        return;
                    }
                }
            }

        }

        // 监测目前倾斜木块，判断是否结束游戏，更改gameover状态
        this.funCheckGameOver();

        // 更新玩家位置
        if (!this.player.isMovingRight) {
            this.player.y += this.player.speedY;
            if (this.player.y <= (this.height - (this.blocks[0].height * this.playerMoveRange)) || this.player.y + this.player.height >= this.height - this.blocks[0].height * 2 - (this.player.height / 5)) {
                this.player.speedY = -this.player.speedY;
            }
        } else {
            this.player.x += 5;
            if (this.player.x >= this.width) //不能出手机边界
            {
                this.player.x = this.iconSize;
                this.player.y = this.height * (1 - this.percentage * 2);
                this.player.isMovingRight = false;
            }
        }

        // 更新方块位置
        this.blocks.forEach(block => {
            block.x += block.speedX;
            block.y += block.speedY;
            block.speedY += 0.1;
            if (block.angle !== 0) {
                this.context.save();
                this.context.translate(block.x + block.width / 2, block.y + block.height / 2);
                this.context.rotate(block.angle);
                this.context.translate(-block.width / 2, -block.height / 2);
                this.context.drawImage(block.cube, block.x, block.y, block.width, block.height);
                this.context.restore();
            }
        });

        // 检测方块碰撞
        this.blocks.forEach((block, index) => {
            this.blocks.forEach((otherBlock, otherIndex) => {
                if (index !== otherIndex && this.funCheckCollision(block, otherBlock)) {
                    if (block.speedY > 0 && block.y + block.height <= otherBlock.y + otherBlock.height) {
                        block.y = otherBlock.y - block.height;
                        block.speedY = 0;
                    }
                }
            });

            if (block.y + block.height > this.height) {
                block.y = this.height - block.height;
                block.speedY = 0;
            }
        });

        // 检测玩家与方块的碰撞
        let collidedBlocks = [];
        this.blocks.forEach(block => {
            if (this.funCheckCollision(this.player, block)) {
                collidedBlocks.push(block);
            }
        });
        if (collidedBlocks.length > 0) {
            this.funHandleCollision(collidedBlocks);
        }
        
        this.drawFrameContent();
        requestAnimationFrame(this.drawAnimate.bind(this));
    }
    // 绘制帧内容
    drawFrameContent() {
        this.context.clearRect(0, 0, this.width, this.height);
        this.context.drawImage(this.background, 0, 0, this.width, this.height);
        this.context.drawImage(this.time_icon, this.iconSize * 2, this.iconSize / 2, this.iconSize, this.iconSize);
        this.context.drawImage(this.pig, this.player.x, this.player.y, this.player.width, this.player.height);
        this.context.fillStyle = 'black';
        this.context.font = `${this.size_1}px Arial`;
        this.context.textAlign = 'center';
        this.context.fillText(`${this.completeTime}s`, this.iconSize * 5 / 2, this.iconSize * 2); // 因图片大小限制，起始位置x有空白偏差，字体x增加半个iconSize
        this.blocks.forEach((block, index) => {

            if (block.status == 'floor') {
                this.context.fillStyle = '(255,0,0,0)';
            } else {
                this.drawBlock(block)
            }

        });
    }
    
    //失败弹窗显示
    showLosePopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        // 创建 Lose 类实例，并传入当前 Canvas 的上下文和尺寸，以及重新开始的回调函数
        let losePopup = new Lose(this.canvas, this.width, this.height,this.score, this.funRestartGame.bind(this), this.funBackHome.bind(this));
        losePopup.drawPopup(); // 绘制并显示弹窗
    }

    //暂停弹窗显示
    showPausePopup() {
        this.updating = false; // 停止更新
        // 禁用触摸事件
        wx.offTouchStart();
        let pausePopup = new Pause(this.canvas, this.width, this.height, this.funRestartGame.bind(this), this.funContinueGame.bind(this), this.funBackHome.bind(this));
        pausePopup.drawPopup();
    }

    // 判断偏移方块，更改状态
    funCheckGameOver() {
        this.countNum = 0;
        this.blocks.forEach((block, index) => { //检查当前偏移方块数
            if (block.angle !== 0) {
                this.countNum += 1;
            }
            if (this.countNum > 2) {
                this.isUpdating = false
                this.gameOver = true
            }
        })
    }

    funCheckCollision(rect1, rect2) {
        return rect1.x < rect2.x + rect2.width &&
            rect1.x + rect1.width > rect2.x &&
            rect1.y <= rect2.y + rect2.height &&
            rect1.y + rect1.height >= rect2.y;
    }

    // 处理碰撞后的事件
    funHandleCollision(collidedBlocks) {
        if (collidedBlocks.length === 1) {
            let block = collidedBlocks[0];
            if (block.status == 'wood') {
                if (this.countNum === 0 || (this.countNum !== 0 && block.angle !== 0)) { //判断是否有其它存在
                    if (block.angle === 0 || (block.angle !== 0 && this.countNum === 1)) {
                        if (settings.FORCE_OPEN === true) {
                            playWoodHitMusic();
                        }
                        this.player.isMovingRight = false;
                        block.angle = 0;    //bug修复
                        block.speedX = 5;
                        this.score++;
                        this.blocks.forEach(b => {
                            if (b.y < block.y) {
                                b.speedY = 2;
                            }
                        });
                    } else if (block.angle !== 0 && this.countNum === 2) {
                        this.player.isMovingRight = false;
                        block.angle = 0;

                    } else {
                        this.isUpdating = false
                        this.gameOver = true
                    }
                } else {
                    this.isUpdating = false
                    this.gameOver = true
                }
            } else {
                this.player.isMovingRight = false;
            }
        } else if (collidedBlocks.length === 2) {
            const [block1, block2] = collidedBlocks;
            this.player.isMovingRight = false;

            if (block1.angle === 0 && block2.angle === 0) {
                if (block1.y < block2.y) {
                    block1.angle = -Math.PI / 24;
                    block2.angle = Math.PI / 24;
                } else {
                    block1.angle = Math.PI / 24;
                    block2.angle = -Math.PI / 24;
                }
            } else if (block1.angle !== 0 || block2.angle !== 0) {
                if (block1.angle !== 0 && block2.angle !== 0) {
                    this.isUpdating = false
                    this.gameOver = true
                } else {
                    block1.angle = 0;
                    block2.angle = 0;
                }
            }

            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.angleOffset = Math.random() * 0.02 - 0.01;
                }
            });
            this.blocks.forEach(b => {
                if (b.y < block1.y || b.y < block2.y) {
                    b.speedY = 0;
                }
            });
        }

        this.blocks.forEach(b => b.hasCollided = false);
        
        this.player.x = this.iconSize;
        this.player.y = this.height * (1 - this.percentage * 2);
    }

    // 通关进入第二关
    funGoTwo() {
        clearInterval(this.timer); // 停止定时器
        wx.offTouchStart(); // 停止触摸事件监听器
        this.canvas.width = this.canvas.width;
        wx.showToast({
            title: '进入第二关',
            success: (res) => {
            },
            fail: (res) => {
            },
        });
        this.buttonDestroy();
        const two = new Checkpoint(this.canvas);
    }

    //重新开始游戏 函数绑定
    funRestartGame() {
        this.buttonDestroy();
        new Checkpoint_one(this.canvas);
    }

    // 继续游戏 函数绑定
    funContinueGame() {
        this.updating = true; // 恢复更新
        this.isPausing = false;
        this.init();
    }

    // 返回主页 函数绑定
    funBackHome() {
        clearInterval(this.timer); // 停止定时器
        wx.offTouchStart(); // 停止触摸事件监听器
        this.buttonDestroy();
        const Home = new DashBoard(this.canvas);
    }

    //音效打击声
    funAudioPlay() {
        const innerAudioContext = wx.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        innerAudioContext.src = '/audios/percussive.mp3'; // 音频资源地址 
        innerAudioContext.onPlay(() => {
            console.log("播放成功!");
        });
        innerAudioContext.onError((error) => {
            wx.showModal({
                title: "播放出错",
                content: `详细错误信息：${error.errMsg}`,
            });
            console.log("播放出错", error);
        });
    }

    buttonDestroy() {
      this.button.forEach(bt => {
          bt.destroy();
      });
  }
}
